﻿using Microsoft.Win32.TaskScheduler;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TaskScheduler;

namespace ParallelLib.WinTaskScheduler
{
    public class TaskScheduler
    {
        public static void CreateTaskService(string taskName, string vbsRootPath,string[] args)
        {
            TaskService ts = new TaskService();
            Microsoft.Win32.TaskScheduler.Task wsTask = ts.GetTask(taskName);
            if (wsTask != null)
            {
                wsTask.Run(args);
                return;
            }
            string vbsStart = Path.Combine(vbsRootPath, "Start.vbs");//ApiConfig.ExtPath
            TaskDefinition td = ts.NewTask();
            td.RegistrationInfo.Description = taskName;

            //开机后2分钟开始运行任务
            td.Triggers.Add(new BootTrigger { Delay = new TimeSpan(0, 2, 0) });
            //参数1 Interval 间隔：每次重新启动任务之间的时间量。允许的最长时间为31天，允许的最短时间为1分钟
            //参数2 Duration 持续时间：重复模式的持续时间。允许的最短时间是一分钟。如果指定了TimeSpan.Zero，则该模式将无限期地重复。
            //参数3：获取或设置一个布尔值，该值指示正在运行的任务实例在重复模式持续时间结束时停止。
            RepetitionPattern repetition = new RepetitionPattern(new TimeSpan(0, 1, 0), TimeSpan.Zero, true);
            td.Triggers.Add(new DailyTrigger { Repetition = repetition });
            td.Actions.Add(new ExecAction("wscript.exe", vbsStart, null));
            ts.RootFolder.RegisterTaskDefinition(taskName, td);
        }

        public static void DeleteTask(string taskName)
        {
            TaskService ts = new TaskService();
            Microsoft.Win32.TaskScheduler.Task wsTask = ts.GetTask(taskName);
            if (wsTask != null)
            {
                if (wsTask.IsActive)
                {
                    wsTask.Stop();
                }
                wsTask.Folder.DeleteTask(taskName);
            }
        }

        /// <summary>
        /// get all tasks
        /// </summary>
        public static IRegisteredTaskCollection GetAllTasks()
        {
            TaskSchedulerClass ts = new TaskSchedulerClass();
            ts.Connect(null, null, null, null);
            ITaskFolder folder = ts.GetFolder("\\");
            IRegisteredTaskCollection tasks_exists = folder.GetTasks(1);
            return tasks_exists;
        }

        /// <summary>
        /// check task isexists
        /// </summary>
        /// <param name="taskName"></param>
        /// <returns></returns>
        public static bool IsExists(string taskName)
        {
            var isExists = false;
            IRegisteredTaskCollection tasks_exists = GetAllTasks();
            for (int i = 1; i <= tasks_exists.Count; i++)
            {
                IRegisteredTask t = tasks_exists[i];
                if (t.Name.Equals(taskName))
                {
                    isExists = true;
                    break;
                }
            }
            return isExists;
        }

        /// <summary>
        /// create task
        /// </summary>
        /// <param name="creator">创建者</param>
        /// <param name="taskName">计划任务名称</param>
        /// <param name="path">路径</param>
        /// <param name="interval">循环时间</param>
        /// <param name="parameters">参数(格式：aa bb cc)</param>
        /// <param name="stateTime">执行开始时间(格式：2015-12-15T00:00:00)</param>
        public static void CreateTaskScheduler(string creator, string taskName, string path, string interval, string parameters, string stateTime)
        {
            try
            {
                if (IsExists(taskName))
                {
                    DeleteTask(taskName);
                }
                //实例化任务对象
                TaskSchedulerClass scheduler = new TaskSchedulerClass();
                //注：只有Connect之后才能使用
                scheduler.Connect(null, null, null, null);//连接
                //get scheduler folder
                ITaskFolder folder = scheduler.GetFolder("\\");
                //set base attr 
                ITaskDefinition task = scheduler.NewTask(0);
                task.RegistrationInfo.Author = creator;//创建者
                task.RegistrationInfo.Description = "...";//描述

                //set trigger  (IDailyTrigger ITimeTrigger)
                ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME);
                //tt.Repetition.Interval = interval;//循环时间( format PT1H1M==1小时1分钟 设置的值最终都会转成分钟加入到触发器)
                tt.StartBoundary = stateTime;//开始执行时间 格式：2015-12-15T00:00:00

                //set action
                IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
                action.Path = path;
                action.Arguments = parameters;
                task.Settings.ExecutionTimeLimit = "PT0S"; //运行任务时间超时停止任务吗? PTOS 不开启超时
                task.Settings.DisallowStartIfOnBatteries = false;//只有在交流电源下才执行
                task.Settings.RunOnlyIfIdle = false;//仅当计算机空闲下才执行

                IRegisteredTask regTask = folder.RegisterTaskDefinition(taskName, task, (int)_TASK_CREATION.TASK_CREATE, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, "");
                IRunningTask runTask = regTask.Run(null);
                //return runTask.State;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        public static void DeleteTask2(string taskName)
        {
            TaskSchedulerClass ts = new TaskSchedulerClass();
            ts.Connect(null, null, null, null);
            ITaskFolder folder = ts.GetFolder("\\");
            folder.DeleteTask(taskName, 0);
        }
    }
}
